package storage.record;

import java.io.*;

import storage.file.BlockID;
import storage.file.FileManagerFactory;
import utils.Lib;

import config.Config;


/**
 * Heapfile layout:
 * +---------+
 * | record1 |
 * +---------+
 * | record2 |
 * +---------+
 * | ... ... |
 * 
 * record layout:
 *  0            3 4              7
 * +--------------+-----------------+
 * | block number | in-block offset |
 * +--------------+-----------------+
 * 
 * @author baiger
 *
 */
public class HeapFile {
	
	private static final String heapFileName = Config.getString("heapfile", "earlyBird.hf");
	private static RandomAccessFile heapfile;
	
	private static final long recordLength = 8;	// see comments above
	
	static {
		try {
			heapfile = new RandomAccessFile(heapFileName, "rw");
		} catch (FileNotFoundException e) {
			// create a new one
			File file = new File(heapFileName);
			try {
				file.createNewFile();
				heapfile = new RandomAccessFile(file, "rw");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	
	public static Record getRecord(int rid) {
		try {
			heapfile.seek(recordLength * rid);
			byte[] bytes = new byte[8];
			heapfile.read(bytes, 0, 8);
			
			int blockNumber = Lib.bytesToInt(bytes, 0);
			int recordOffset = Lib.bytesToInt(bytes, 4);
			
			String fileName = "";
			int blockOffset = 0;
			try {
				fileName = FileManagerFactory.getFileManager().getFileName(blockNumber);
				blockOffset = FileManagerFactory.getFileManager().getOffsetInFile(blockNumber);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			BlockID block = new BlockID(fileName, blockOffset);
			
			return new Record(rid, block, recordOffset);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
